<?php

namespace App\Repositories;

use App\Events\LikeCreated;
use App\Models\Club;
use App\Models\Comment;
use App\Models\Technician;
use App\Models\User;

class LikeRepository
{
    public function create(User $user, $targetKey, $targetType, $likeType)
    {
        $targetType = $this->getTargetType($targetType);
        $result = \DB::transaction(function () use ($user, $targetKey, $targetType, $likeType) {
            $target = (new $targetType)->where('key', $targetKey)->firstOrFail();
            $exists = $user->likes()
                ->where('target_id', $target->id)
                ->where('target_type', $targetType)
                ->where('like_type', $likeType)
                ->exists();
            if ($exists) {
                return api("已经OK");
            }
            $like = $user->likes()->create([
                'target_type' => $targetType,
                'target_id' => $target->id,
                'like_type' => $likeType,
            ]);
            $likeCount = $target->likes()->where('like_type', $likeType)->count();
            $target->update(['like_count' => $likeCount]);

            //触发点赞事件
            event(new LikeCreated($like));

            return api(RET_OK, MSG_OK, ['like_count' => $likeCount]);
        });

        return $result;
    }

    private function getTargetType($type)
    {
        switch ($type) {
            case 1:
                return Comment::class;
        }
        throw new \InvalidArgumentException("invalid type：$type");
    }
}